using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Reflection;
using Yahoo.API;
using System.Diagnostics;

namespace SimpleGoogleSearch
{
    public partial class _Default : System.Web.UI.Page
    {
        string passPhrase = "Pas5pr@se";        // can be any string
        string saltValue = "s@1tValue";        // can be any string
        string hashAlgorithm = "SHA1";             // can be "MD5"
        int passwordIterations = 2;                  // can be any number
        string initVector = "@1B2c3D4e5F6g7H8"; // must be 16 bytes
        int keySize = 256;                // can be 192 or 128

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["search"]))
                {
                    int page;
                    int.TryParse(Request.QueryString["page"], out page);

                    if (page == 0)
                        page = 1;
                    string k = Request.QueryString["search"];
                    string text = GetResponse(k);
                    Search(text, page);
                }
            }
        }

        /// <summary>
        /// Handles the ServerClick event of the x control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void x_ServerClick(object sender, EventArgs e)
        {
            string val = SetResponse(s.Value);

            Response.Redirect("Default.aspx?search=" + val + "&page=1");
        }

        /// <summary>
        /// Searches the specified text.
        /// </summary>
        /// <param name="text">The text.</param>
        private void Search(string text, int page)
        {
            try
            {
                YahooSearchService yahoo = new YahooSearchService();

                Yahoo.API.WebSearchResponse.ResultSet resultSet = yahoo.WebSearch("YahooExample", text, "any", 5, 10*(page-1) + 1, "all", true, false, "en");
                                
                SetResults(resultSet);

                string a = resultSet.totalResultsAvailable;

                int count;
                int.TryParse(a, out count);

                int pages = count / 5;

                Debug.WriteLine(pages);

                SetNavigation(pages, page);
            }
            catch (Exception)
            {
            }            
        }

        /// <summary>
        /// Gets the space label.
        /// </summary>
        /// <returns></returns>
        private Label GetSpaceLabel()
        {
            Label l = new Label();
            l.Text = "&nbsp;&nbsp;";

            return l;
        }

        /// <summary>
        /// Sets the navigation.
        /// </summary>
        /// <param name="pages">The pages.</param>
        /// <param name="page">The page.</param>
        private void SetNavigation(int pages, int page)
        {
            int start = 1;
            int stop = pages;

            if (page > 5)
                start = page - 5;

            if (page < pages - 5)
                stop = page + 5;

            navigation.Controls.Clear();

            //add previous
            HyperLink h = new HyperLink();
            h.NavigateUrl = "Default.aspx?search=" + Request.QueryString["search"] + "&page=" + (page - 1);
            h.Text = "<<<";
            h.CssClass = "link";
            if (page == 1)
            {
                h.Enabled = false;
                h.CssClass = "linkDisabled";
            }          

            navigation.Controls.Add(h);

            //add space
            navigation.Controls.Add(GetSpaceLabel());

            for (int i = start; i <= stop; i++)
            {
                if (i == page)
                {
                    HyperLink h1 = new HyperLink();
                    h1.NavigateUrl = "Default.aspx?search=" + Request.QueryString["search"] + "&page=" + i;
                    h1.Text = i.ToString();
                    h1.Enabled = false;
                    h1.CssClass = "linkActual";

                    navigation.Controls.Add(h1);
                }
                else
                {
                    HyperLink h1 = new HyperLink();
                    h1.NavigateUrl = "Default.aspx?search=" + Request.QueryString["search"] + "&page=" + i;
                    h1.Text = i.ToString();
                    h1.CssClass = "link";

                    navigation.Controls.Add(h1);
                }

                //add space
                navigation.Controls.Add(GetSpaceLabel());
            }

            //add next
            HyperLink h2 = new HyperLink();
            h2.NavigateUrl = "Default.aspx?search=" + Request.QueryString["search"] + "&page=" + (page + 1);
            h2.Text = ">>>";
            h2.CssClass = "link";
            if (page == pages)
            {
                h2.Enabled = false;
                h2.CssClass = "linkDisabled";
            }           

            navigation.Controls.Add(h2);
        }

        /// <summary>
        /// Sets the results.
        /// </summary>
        /// <param name="result_">The result_.</param>
        private void SetResults(Yahoo.API.WebSearchResponse.ResultSet result_)
        {
            resultPanel.Controls.Clear();

            if (result_ != null)
            {
                if (result_.Result != null)
                {
                    Control uc;
                    Type ucType;
                    PropertyInfo ucType_TextValue;

                    foreach (Yahoo.API.WebSearchResponse.ResultType result in result_.Result)
                    {
                        uc = LoadControl("SearchResult.ascx");

                        ucType = uc.GetType();

                        ucType_TextValue = ucType.GetProperty("Title");
                        ucType_TextValue.SetValue(uc, result.Title, BindingFlags.SetProperty, null, null, null);

                        ucType_TextValue = ucType.GetProperty("Description");
                        ucType_TextValue.SetValue(uc, result.Summary, BindingFlags.SetProperty, null, null, null);

                        ucType_TextValue = ucType.GetProperty("Link");
                        ucType_TextValue.SetValue(uc, result.Url, BindingFlags.SetProperty, null, null, null);

                        resultPanel.Controls.Add(uc);
                    }
                }
            }
        }

        /// <summary>
        /// Sets the response.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <returns></returns>
        private string SetResponse(string text)
        {
            text = text.Replace("#", "_");

            return text;
        }

        /// <summary>
        /// Gets the response.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <returns></returns>
        private string GetResponse(string text)
        {
            text = text.Replace("_", "#");

            return text;
        }
    }
}
